import { typeArrClass } from '../../../utils/util'
const towxml = require("../../../towxml/index");
let rawData = []
Page({

  /**
   * 页面的初始数据
   */
  data: {
    noneDataTip: '请在咨询客服老师前认真浏览以上常见问题。务必提前告知学校+学号+问题描述。并截图问题界面给客服老师，以便高效处理问题;',
    name: '', // 当前点击的折叠面板项
    helpData: [], // 模拟数据项
    inputFocus: false, // 输入款是否获得焦点
    location: 1, // 1代表登录帮助,2代表我的帮助
    appMsg: {
      show: false,
      type: 'none'
    },
    pageLoading: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { page } = options
    let location = 1
    switch (page) {
      case 'my':
        location = 2
        break;
      case 'login':
        location = 1
        break;
    }
    this.data.location = location
    this.getIssue({ location })
  },
  towxml (str, type = 'html') {
    try {
      let result = towxml(str, type, {
        events: {
          tap: (e) => {
            if (e.target.dataset.data && e.target.dataset.data.attr.src) {
              wx.previewImage({
                current: e.target.dataset.data.attr.src,
                urls: [e.target.dataset.data.attr.src],
                fail: res => {
                  wx.showModal({
                    title: '图片预览失败~',
                    content: ''
                  })
                }
              })
            }
          },
          longpress: e => {
            try {
              if (!e || !e.currentTarget || !e.currentTarget.dataset || !e.currentTarget.dataset.data || !e.currentTarget.dataset.data.child[0]) { return }
              wx.setClipboardData({
                data: e.currentTarget.dataset.data.child[0].text,
                success (res) {
                  wx.getClipboardData({
                    success: (res) => {
                      console.log(res.data) // data
                    }
                  })
                },
                fail: (err = '') => {
                  wx.showToast({
                    title: '复制失败',
                    icon: 'none'
                  })
                  console.log(err)
                }
              })
            } catch (err) {
              console.log(err)
            }
          },
        }
      });
      return result
    } catch (err) {
      console.error('富文本解析出错: ', err)
      wx.showToast({
        title: '内容解析错误,请刷新再试',
        icon: 'none',
        duration: 2000
      })
    }
  },
  /**
   * @see 获取问题
   */
  getIssue (params) {
    wx.showLoading({
      title: '加载中'
    })
    wx.$API['person/getIssue'](params).then(res => {
      const newArr = typeArrClass(res.data, 'issueCategoryId')
      newArr.forEach(v => {
        v.data.forEach(detail => {
          Object.defineProperty(detail, 'noEdit', {
            configurable: false,
            enumerable: true,
            get: () => detail.issueContent
          })
        })
      })
      rawData = JSON.parse(JSON.stringify(newArr))
      this.setData({
        helpData: newArr,
        pageLoading: false
      })
      wx.hideLoading()
    })
      .catch(error => {
        wx.hideLoading()
        wx.showToast({
          title: error,
          icon: 'none'
        })
        this.setData({
          // appMsg: {
          //   show: true, type: 'none',
          // }
          pageLoading: false
        })
        console.log('获取问题列表失败', error)
      })
  },
  /**
   * @see 展开联系客服
   */
  helpClick (e) {
    const { name } = this.data
    const newName = e.currentTarget.dataset.name
    this.setData({
      name: newName === name ? '' : newName
    })
  },
  /**
   * @see 加载失败,重试
   */
  clickMsgButton () {
    this.getIssue({ location: this.data.location })
  },
  /**
   * @see 获取焦点
   */
  inputGetFocus () {
    this.setData({
      inputFocus: true
    })
  },

  /**
   * @see 搜索 - 从原始数据中搜索,搜索后设置回helpData中显示
   */
  search (e) {
    const { value } = e.detail
    // 保存的最开始的数据
    // 克隆一份
    let newData = JSON.parse(JSON.stringify(rawData))
    if (value.trim()) {
      newData.forEach(v => {
        v.data = v.data.filter(detail => {
          return detail.issueTitle.indexOf(value) !== -1 || detail.noEdit.indexOf(value) !== -1
        })
      })
    } else {
      newData = rawData.length > 0 ? rawData : newData
    }
    newData = newData.filter(v => v.data.length)
    this.setData({
      helpData: newData,
      name: ''
    })
  },
  /**
   * @see 点击列表项,同时渲染富文本
   */
  itemClick (e) {
    const { helpData } = this.data
    let { name, detail } = e.currentTarget.dataset
    name = name === this.data.name ? '' : name
    // 只有没被towxml方法处理过的才处理,减少性能损耗
    if (!(typeof detail.issueContent === 'object')) {
      helpData.forEach(v => {
        v.data.forEach(vd => {
          // 找到当前点击的那一项,将其解析
          if (vd.id === name) {
            let str = vd.issueContent.replace(/<img/g, '<img style="min-width:100%;height:100%" ')
            vd.issueContent = this.towxml(str)
          }
        })
      })
      // 将解析后的富文本放回去,否则页面无响应
      this.setData({
        helpData
      })
    }
    this.setData({
      name
    })
  },
  //跳转到小程序的其他页面
  jumpPage(event) {
    wx.navigateTo({
      url: event.currentTarget.dataset.url,
    })
  },
})
